package com.lv.service.impl;

import com.lv.entity.LoginUser;
import com.lv.entity.User;
import com.lv.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


import java.util.List;


/**
 * Created with IntelliJ IDEA.
 * <p>
 *
 * </p>
 *
 * @Author: 凉薄
 * @Date: 2022/01/08/16:28
 * @Description:
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    UserService userService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getByName(username);
        if(user==null){
            throw new UsernameNotFoundException("用户名错误！！");
        }
        return new LoginUser(user.getId(),user.getUsername(),user.getPassword(),user.getStatus(),getUserAuthorities(user.getId()));
    }

    public List<GrantedAuthority> getUserAuthorities(Long id) {
        String userAuthorities = userService.getUserAuthorities(id);
        return AuthorityUtils.commaSeparatedStringToAuthorityList(userAuthorities);
    }
}
